package glashart2xmltv;

import static glashart2xmltv.Grabber.MAX_DAY_SEGMENTS;
import static java.util.Calendar.DAY_OF_MONTH;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author Jeroen Peschier
 * @version $Id: ImportJob.java 2 2013-02-09 11:54:47Z peschierj@gmail.com $
 */
public class ImportJob {
	
	private static final Locale DUTCH_LOCALE = new Locale("nl", "NL");	
	private static final Log log = LogFactory.getLog(ImportJob.class);
	
	public static void main(String[] args) {
		try {
			if (args.length >= 1) {
				Config.initialise(args[0]);
			} else {
				Config.initialise();
			}
			ImportJob job = new ImportJob();
			job.doImport();
		} catch (Exception e) {
			System.out.println();
			log.error("Execution failed in main.", e);
		}
	}
	
	public ImportJob() {}
	
	public void doImport() {
		try {
			Config config = Config.getInstance();
			Grabber grabber = new Grabber();
			OutputStream out = new FileOutputStream(config.getOutputFile());
			XmltvBuilder builder = new XmltvBuilder();
			
			for (int day = 0; day < config.getNumberOfDays(); day++) {
				Date date = getDate(day);
				for (int daySegment = 0; daySegment < MAX_DAY_SEGMENTS; daySegment++) {
					Map<String, Collection<GuideEntry>> entries = grabber.getBaseGuideEntries(date, daySegment);
	
					for (String channel : entries.keySet()) {

						if (config.getChannels().contains(channel)) {
							log.info("Fetching programme info for channel [" + channel + "] and offset [" + daySegment + "].");
							
							if (daySegment == 0) { // this ensures that we only add the channel once
								builder.addChannel(channel, channel, null);
							}
							
							for (GuideEntry entry : entries.get(channel)) {
								log.info("Processing entry [" + entry + "].");
								try {
									ProgrammeEntry programme = grabber.getProgrammeInfo(entry.getId());
									log.info("Retrieved programme [" + programme + "].");
									builder.addProgrammeEntry(channel, programme);
								} catch (Exception e) {
									log.error("Failed to retrieve programme.", e);
								}
							}
							
						} else {
							log.debug("Channel not whitelisted, skipping thusly.");
						}
					}
				}
			}
			
			builder.serialise(out);
			out.close();

		} catch (Exception e) {
			log.error("Import failed.", e);
		}
	}
	
	private Date getDate(int daysFromToday) {
		Calendar calendar = Calendar.getInstance(DUTCH_LOCALE);
		calendar.add(DAY_OF_MONTH, daysFromToday);
		return calendar.getTime();
	}
}